package com.ruoyi.source.websocket.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.source.service.CheckRecordService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/ww/server")
public class WebSocketServers {
    //concurrent  线程安全  用来存放每个客户端对应的websocket对象
    private static int onlineCount = 0;
    private static  ConcurrentHashMap<String,WebSocketServers> websocketMap=new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    @Autowired
    private  CheckRecordService checkRecordService;
    private static  CheckRecordService isrcRecordMapper;
    @PostConstruct
    public void init(){
        WebSocketServers.isrcRecordMapper=checkRecordService;
    }

    private Session session;

    public static void sendAllMessage(String message) throws IOException {
        ConcurrentHashMap.KeySetView<String, WebSocketServers> userIds = websocketMap.keySet();
        System.out.println(userIds);
        for (String userId : userIds) {
            WebSocketServers webSocketServers = websocketMap.get(userId);
            webSocketServers.session.getBasicRemote().sendText(message);
            System.out.println("webSocket实现服务器主动推送成功userIds===="+userIds);
        }
    }
    //连接建立成功调用的方法
  private String userId="1111";
    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        if(websocketMap.containsKey(userId)){
            websocketMap.remove(userId);
            websocketMap.put(userId,this);
            //加入set中
        }else{
            websocketMap.put(userId,this);
            //加入set中

        }
        log.info("进入连接开始查找数据");
        try {
            Map<String,Object> map = new HashMap<>();
            //map.put("server",iSrcCropInfoService.SelectCropType());
            map.put("pie", isrcRecordMapper.selectCheckRecords());
            JSONObject jsonObject =  new JSONObject(map);
            sendMessage(jsonObject.toString());
        } catch (Exception e) {
            log.error("网络异常!!!!!!");
        }

    }

    //实现服务器主动推送
    public void sendMessage(String message){
        try {
            this.session.getBasicRemote().sendText(message);
            System.out.println("webSocket实现服务器主动推送成功");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
